package com.kongming.kmdm.ws.rest.coder;

import com.kongming.kmdm.ws.rest.msg.SubRequestMsg;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

/**
 * 将请求信息转换成server接受的消息类型
 *
 * @author Alex
 * @des
 * @date 2015年4月30日
 */
public class SubscribeMsgDecoder implements Decoder.Text<SubRequestMsg> {

    private static Logger logger = LoggerFactory.getLogger(SubscribeMsgDecoder.class);

    @Override
    public void init(EndpointConfig config) {

    }

    @Override
    public void destroy() {

    }

    @Override
    public SubRequestMsg decode(String s) throws DecodeException {

        return new SubRequestMsg(JSONObject.fromObject(s));
    }

    @Override
    public boolean willDecode(String s) {

        try {
            logger.info("resv msg: " + s);
            JSONObject json = JSONObject.fromObject(s);
            //            if (SubRequestMsg.isValidCmd (json) && SubRequestMsg.isValidMsg (json)) {
            if (SubRequestMsg.isValidCmd(json)) {
                //请求参数合法
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }

}
